//
//  WelcomeFirstView.swift
//  ShouChong
//
//  Created by 陈友文 on 2024/6/11.
//

import SwiftUI
import MMDrawerController

struct WelcomeFirstView: View {
    @ObservedObject var welcomeVM:WelcomeVM = WelcomeVM()
    struct AgeItem:Identifiable {
        var id:String = UUID().uuidString
        var title:String
    }
    @State private var isAgree:Bool = false
    @State private var anim:Bool = false
    @State private var x:CGFloat = 0
    @State private var ageList:[AgeItem] = [
        AgeItem(title: "60后"),
        AgeItem(title: "70后"),
        AgeItem(title: "80后"),
        AgeItem(title: "90后"),
        AgeItem(title: "00后"),
        AgeItem(title: "10后"),
    ]
    var confirmBlock:() -> Void
    @State private var selectIndex:Int = 0
    @State private var ageIndex:Int = 0
    let itemList:[GridItem] = [
        GridItem(.flexible(), spacing: 12, alignment: nil),
        GridItem(.flexible(), spacing: 12, alignment: nil),
        GridItem(.flexible(), spacing: 12, alignment: nil),
    ]
    @AppStorage("curren_main_color") var currentMainColor = "color_main_01"
    @AppStorage("user_age") var userAge = "60后"
    @AppStorage("user_sex") var userSex = "0"
    @AppStorage("login_token") var loginToken:String = ""
    @AppStorage("user_avator") var userAvatar = "user_header_01"
    @AppStorage("user_avator_base64") var avatorBase64 = ""
    @AppStorage("user_name") var userName = ""
    @State private var showLoginView:Bool = false
    var body: some View {
        VStack(content: {
            Text("完善您的基本资料")
                .modifier(MainTextModifier(fontSize: 28, fontWeight: .bold, foreColor: Color("color_text_black")))
                .padding(.top,40)
                .padding(.bottom,40)
            HStack {
                Text("设置您的性别")
                    .modifier(MainTextModifier(fontSize: 16, fontWeight: .bold, foreColor: Color("color_text_black")))
                Spacer()
            }
            .padding(.bottom,12)
            .padding(.horizontal,20)
            HStack {
                Spacer()
                Image("welcome_man")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width:140,height: 200)
                    .background(selectIndex == 0 ? Color(currentMainColor):Color("color_bg"))
                    .cornerRadius(10)
                    .onTapGesture {
                        let generator = UIImpactFeedbackGenerator(style: .light)
                        generator.prepare()
                        generator.impactOccurred()
                        selectIndex = 0
                        currentMainColor = "color_main_01"
                    }
                    
                Spacer()
                Spacer()
                Image("welcome_woman")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width:140,height: 200)
                    .background(selectIndex == 1 ? Color(currentMainColor):Color("color_bg"))
                    .cornerRadius(10)
                    .onTapGesture {
                        let generator = UIImpactFeedbackGenerator(style: .light)
                        generator.prepare()
                        generator.impactOccurred()
                        selectIndex = 1
                        currentMainColor = "color_main_02"
                    }
                Spacer()
            }
            .padding(.bottom,40)
            HStack {
                Text("设置您的年龄")
                    .modifier(MainTextModifier(fontSize: 16, fontWeight: .bold, foreColor: Color("color_text_black")))
                Spacer()
            }
            .padding(.bottom,12)
            .padding(.horizontal,20)
            AgeItemView
                .padding(.bottom,40)
            ShakeButton(label: Text("下一步").modifier(MainButtonModifier(width: kScreenWidth - 50))
            ) {
                if !self.isAgree {
                    let generator = UIImpactFeedbackGenerator(style: .medium)
                    generator.prepare()
                    generator.impactOccurred()
                    withAnimation(.easeInOut(duration: 0.1)) {
                        x = 6
                    } completion: {
                        withAnimation(.easeInOut(duration: 0.2)) {
                            x = -6
                        } completion: {
                            withAnimation(.easeInOut(duration: 0.1)) {
                                x = 0
                            }
                        }
                    }
                    return
                }
                self.userAge = self.ageList[self.ageIndex].title
                self.selectIndex == 0 ? (self.userSex = "0") : (self.userSex = "1")
                self.confirmBlock()
            }
            ShakeButton(label: Text("已有账号？直接登录").modifier(MainTextModifier(fontSize: 14, fontWeight: .medium, foreColor: Color("color_text_black")))) {
                if !self.isAgree {
                    let generator = UIImpactFeedbackGenerator(style: .medium)
                    generator.prepare()
                    generator.impactOccurred()
                    withAnimation(.easeInOut(duration: 0.1)) {
                        x = 6
                    } completion: {
                        withAnimation(.easeInOut(duration: 0.2)) {
                            x = -6
                        } completion: {
                            withAnimation(.easeInOut(duration: 0.1)) {
                                x = 0
                            }
                        }
                    }
                    return
                }
                showLoginView.toggle()
            }
            .padding(.top,6)
            Spacer()
            HStack{
                Image(systemName: isAgree ? "circle.circle.fill" : "circle")
                    .foregroundColor(Color(currentMainColor))
                    .onTapGesture {
//                        withAnimation {
                            isAgree.toggle()
//                        }
                    }
                Link(destination: URL(string: "https://docs.qq.com/doc/DQWdHV2V2ZnVvSVlj")!, label: {
                    Text("同意《撸了么App用户隐私政策》")
                        .modifier(MainTextModifier(fontSize: 12, fontWeight: .light, foreColor: Color("color_text_black")))
                })
            }.padding(.bottom,4)
//                .animation(.easeInOut(duration: 1).repeatCount(3, autoreverses: true),value: x)
                .offset(x:x)
        })
        .overlay(alignment: .topTrailing) {
            ShakeButton(label: Text("跳过").modifier(MainTextModifier(fontSize: 14, fontWeight: .medium, foreColor: Color("color_text_black")))) {
                if !self.isAgree {
                    let generator = UIImpactFeedbackGenerator(style: .medium)
                    generator.prepare()
                    generator.impactOccurred()
                    withAnimation(.easeInOut(duration: 0.1)) {
                        x = 6
                    } completion: {
                        withAnimation(.easeInOut(duration: 0.2)) {
                            x = -6
                        } completion: {
                            withAnimation(.easeInOut(duration: 0.1)) {
                                x = 0
                            }
                        }
                    }
                    return
                }
                jumpToHomeView()
            }.offset(x:-20,y:10)
        }
        .sheet(isPresented: $showLoginView, content: {
            LoginView()
        })
    }
    
    var AgeItemView:some View {
        LazyVGrid(columns: itemList, content: {
            ForEach(0..<ageList.count,id:\.self) { index in
                Text(ageList[index].title)
                    .foregroundColor(ageIndex == index ? Color("color_text_white") : Color("color_text_black"))
                    .padding(.horizontal,26)
                    .padding(.vertical,10)
                    .background(ageIndex == index ? Color(currentMainColor) :Color.white)
                    .cornerRadius(10)
                    .padding(.bottom,6)
                    .onTapGesture {
                        let generator = UIImpactFeedbackGenerator(style: .light)
                        generator.prepare()
                        generator.impactOccurred()
                        ageIndex = index
                    }
            }
        })
    }
    
    private func login() {
        
    }
    
    private func jumpToHomeView() {
        userAvatar = "user_header_01"
        avatorBase64 = UIImage(named: "user_header_01")?.base64 ?? ""
        userName = RandomNameTool.getName()
        let sendData = [
            "name":userName,
            "age":"90后",
            "uid":UUID().uuidString,
            "vip":"0",
            "image":UIImage(named: "user_header_01")?.base64 ?? "",
            "sex":"0"
        ]
        welcomeVM.firstRegist(sendData: sendData) { res in
            guard let token = res as? String else {
                YWToast.show(text: "发生错误,请稍等")
                return
            }
            loginToken = token
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                let vc = BaseNavController(rootViewController: HomeViewController())
                let settingVC = OpenNavViewController(rootViewController: SettingViewController())
                let mmVC = MMDrawerController(center: vc, leftDrawerViewController:settingVC)
                mmVC?.openDrawerGestureModeMask = .all
                mmVC?.closeDrawerGestureModeMask = .all
                mmVC?.showsShadow = true
                mmVC?.maximumLeftDrawerWidth = 200
                mmVC?.shadowRadius = 5
                mmVC?.shadowColor = .gray.withAlphaComponent(0.4)
                mmVC?.shouldStretchDrawer = false
                UIApplication.shared.keyWindow?.rootViewController = mmVC
            }
        } failBlock: { error, code in
            YWToast.show(text: "发生错误,请稍等")
        }
    }
    
   
}
